/**
 * @description utils controller
 * @author
 */

const { ErrorModel, SuccessModel } = require('../model/ResModel');
const { uploadFileSizeFailInfo } = require('../model/ErrorInfo');
const fse = require('fs-extra');
const path = require('path');
//存储目录
const DIST_FOLDER_PATH = path.join(__dirname, '..', '..', 'uploadFiles');
// 文件最大体积
const MAX_SIZE = 1024 * 1024 * 1024;

//是否创建目录
fse.pathExists(DIST_FOLDER_PATH).then(exist=>{
    if(!exist){
        fse.ensureDir(DIST_FOLDER_PATH);
    }
});


async function saveFile({ name, type, size, filePath }) {
    // 文件太大的的情况
    if (size > MAX_SIZE) {
        // 删掉再返回失败 因为存在了硬盘里
        await fse.remove(filePath);
        return new ErrorModel(uploadFileSizeFailInfo);
    }
    // 移动文件
    const fileName = Date.now() + '.' + name;
    const disFilePath = path.join(DIST_FOLDER_PATH, fileName); //目的地
    await fse.move(filePath, disFilePath);

    //返回信息

    return new SuccessModel({
        url: '/' + fileName,
    });
}

module.exports = {
    saveFile,
};
